<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace yiike\credit;

use Yii;
/**
 * Description of Credit
 *
 * @author dragon
 */
class Credit extends \yii\base\Component {
    
    function get($user_id) {
        $model = models\Credit::findOne($user_id);
        $labels = $model->attributeLabels();
        $data = [
            'value1' => ['name' => $labels['value1'], 'value' => $model->value1],
            'value2' => ['name' => $labels['value2'], 'value' => $model->value2],
            'value3' => ['name' => $labels['value3'], 'value' => $model->value3],
        ];
        return $data;
    }
    
    function update($user_id, $value1=0, $value2=0, $value3=0, $memo='', $union_id=0, $union_from='') {
        
        $model = models\Credit::findOne($user_id);
        if ($model == null) {
            return null;
        }
        
        $recordModel = new models\CreditRecord();
        $recordModel->user_id = $user_id;
        
        $model->value1 += $value1;
        $model->value2 += $value2;
        $model->value3 += $value3;

        $recordModel->value1  = $value1;
        $recordModel->value2  = $value2;
        $recordModel->value3  = $value3;
        $recordModel->blance1  = $model->value1;
        $recordModel->blance2  = $model->value2;
        $recordModel->blance3  = $model->value3;
        $recordModel->union_id = $union_id;
        $recordModel->union_from = $union_from;
        $recordModel->memo = $memo;

        $trans = $model->getDb()->beginTransaction();
        try {
            if ($recordModel->save()) {
                if ($model->save()) {
                    $trans->commit();
                }
            }
            $trans->rollBack();
        } catch (\yii\base\Exception $e) {
            $trans->rollBack();
            throw new \yii\base\Exception("余额写入数据库异常");
        }
    }
}
